<?php

namespace app\index\controller;

use think\Validate;
use app\index\model;


class out extends \think\Controller
{
	public function index()
	{
		//
		
		$ajax = input("ajax",0);
		if($ajax == 1)
		{
			$limit = input("limit",10);
			#获取记录
			$rs = db()->name("out")
			->order("id DESC")
			->paginate($limit);
			// 获取分页显示
			$page = $rs->render();
			
			$rs = $rs->all();
			$total = db()->name("out")->count();
			
			if($ajax)
			{
				$__str = '{"code":0,"msg":"","count":'.$total . ',"data":';
				$__str .= json_encode($rs);
				$__str .= '}';
				echo $__str;
			}
			exit;			
		}
		return view();
	}
	public function add()
	{
		
		return view();
	}
	
	public function doadd()
	{
		$input = array();
		$input['user_id'] = intval(input("post.user_id"));
		$input['data'] = trim(input("post.data"));
		$input['addtime'] = input("post.addtime");
		
		if(!$input['addtime'])
		{
			$input['addtime'] = date('Y-m-d H:i:s');
		}
		
		$rule = [
		'addtime' => 'require|date',
		'user_id' => 'require|number',
		'data' => 'require'
		];
		
		$validate = new Validate($rule);
		if(!$validate->check($input))
		{
			$msg = $validate->getError();
			json(array('msg' => $msg, 'status'=>0));	
		}
		
		//处理 data 数据
		$mtime = strtotime($input['addtime'] . " ". date("H:i:s") );
		$rec = array();
		
		//测试数据
		//$input['data'] = "早餐 , 包子, 5.3";
		

		$tmp = explode("\n", $input['data']);
		$typename = $title = $money = "";
		//字段分隔符
		if(false === strpos($input['data'],','))
		{
			$sep = ' ';
		}
		else
		{
			$sep = ',';
		}
		foreach($tmp as $k => $v)
		{
			$v = trim($v);
			if(!$v || $v{0} == '#')
			{
				continue;
			}
			
			$vv = explode($sep, $v);
			$typename = isset($vv[0]) && $vv[0] ? trim($vv[0]) : $typename;
			$title = isset($vv[1]) && $vv[1] ? trim($vv[1]) : $title;
			$money = isset($vv[2]) ? trim($vv[2]) : $money;
			
			$rt = [
			'user_id' => $input['user_id'],
			'addtime' => $input['addtime'],
			'mtime' => $mtime,
			'typename' => $typename,
			'title' => $title,
			'money' => $money,
			];
			$rec[] = $rt;			
		}
		db()->name("out")->insertAll($rec);
		$total = count($rec);
		json(array('msg' => "添加消费支出成功,共添加:{$total}条", 'status'=>1));	
		dump($rec);
		
	}
}
